
#include "staffball.h"
#include "resourcemanager.h"
#include "gamemanager.h"
#include "frameanimation.h"
#include "CCSkeletalSprite.h"
#include "gamedatamanager.h"
#include "gamescene.h"

static const float STAFF_BALL_SPEED = 450.0f;

#define __super         ArrowBullet

StaffBallBullet::StaffBallBullet(
		const CCPoint& from,
		const CCPoint& to,
		EquipmentAttribute *attr,
		GameScene *scene):
__super(from, to, attr)
, _gameScene(scene)
, animation(nullptr) {
	velocity = ccp(STAFF_BALL_SPEED, 0.0f);
	if (src.x > dst.x) {
		velocity.x = -velocity.x;
	}

	velocity.y = 0.5f * GRAVITY * static_cast<float>(fabs(dst.x - src.x)) / static_cast<float>(fabs(velocity.x));

	_damageType = GDM->getWeaponDamageType(attr->projectileType);
}

StaffBallBullet::~StaffBallBullet() {
}

void StaffBallBullet::init() {
	static const char *fx_names[] = {
			"fx_fire_ball",
			"fx_ice_ball",
			"fx_poison_ball",
			"fx_thunder_ball",
			"fx_dark_ball",
			"fx_holy_ball",
	};

	animation = RM->createAnimation(fx_names[(int) _damageType - (int) DamageType::fire], position);
	_gameScene->addNode(animation);
}

bool StaffBallBullet::update(float ticks) {
	bool ret = true;

	position.x += velocity.x * ticks;
	position.y += velocity.y * ticks;
	velocity.y -= GRAVITY * ticks;
	animation->setPosition(position);

	float rotation = -180.0f * ccpToAngle(velocity) / static_cast<float>(M_PI);
	animation->setRotation(rotation);

	animation->update(ticks);

	if ((src.x <= dst.x && position.x >= dst.x) || (src.x >= dst.x && position.x <= dst.x)) {
		animation->removeFromParent();

		static const char *HIT_FX_NAMES[] = {
				"fx_fire_hit",
				"effects_ice_target",
				"fx_poison_hit",
				"fx_thunder_hit",
				"effects_dark_target",
				"fx_holy_hit",
		};

		FrameAnimation *fxHit = RM->createAnimation(HIT_FX_NAMES[(int) _damageType - (int) DamageType::fire], position);
		fxHit->setLoop(false);
		fxHit->setZOrder(static_cast<int>(GM->screenSize.height - position.y));

		_managedGameNodeInfo.node = fxHit;
		_gameScene->addOneTimeNode(_managedGameNodeInfo);

		ret = false;
	}

	return ret;
}
